package com.xiaoyung.easyisapisdk.common.util;

import java.math.BigDecimal;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;

public class JSONUtils {
	public static String objectToJsonString(Object payload) {
    	return objectToJsonString(payload,JSONWriter.Feature.WriteMapNullValue);// 默认就是日期字符串无需 JSONWriter.Feature.WriteDateUseDateFormat
    }
    
    public static String objectToJsonString(Object payload,JSONWriter.Feature ... features) {
		if (payload == null) {
			return null;
		}
		if(payload instanceof String && ((String)payload).length()==0) {
			return null;
		}
		return JSON.toJSONString(payload,features);
	}
    
    
    public static Object jsonStringToObject(String content) {
    	if(StringUtils.isEmpty(content)) {
    		return null;
    	}
		Object response = null;
		content = content.trim();
		if(content.startsWith("{") && content.endsWith("}") || content.startsWith("[") && content.endsWith("]")){
			response = JSON.parse(content,JSONReader.Feature.AllowUnQuotedFieldNames);//允许字段名不加引号
		}else if(content.startsWith("\"")) {
			response = content.substring(1,content.length()-1);
			response = ((String)response).replaceAll("\\\\\"","\"");
		}else if(content.equals("true") || content.equals("false")) {
			response = Boolean.valueOf(content);
		}else if(content.matches("\\-?\\d+")) {
			Long value = Long.valueOf(content);
			if (value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE) {
				response =  value.intValue();
			}else {
				response = value;
			}
		}else if(content.matches("\\-?\\d+\\.\\d+")) {
			response = new BigDecimal(content);
		}else if(content.equals("null")) {
			response = null;
		}else {
			response = content;
		}
		return response;
	}
}
